package cn.edu.nit.security.controller;

import cn.edu.nit.sys.utils.R;
import com.wf.captcha.ArithmeticCaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
public class CodeController {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @GetMapping("/code")
    public void getCode(HttpServletResponse response) throws IOException {
        String uuid = UUID.randomUUID().toString();
        response.addHeader("Access-Control-Expose-Headers", "uuid");
        response.addHeader("uuid", uuid);
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/gif");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(140, 36);
        captcha.setLen(2);
        String rs = captcha.text();
        redisTemplate.opsForValue().set(uuid, rs, 2, TimeUnit.MINUTES);
        captcha.out(response.getOutputStream());
    }
}
